﻿<!DOCTYPE html>
<!--[if IE]><![endif]-->
<html>
  
  <head>
    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async="" src="https://www.googletagmanager.com/gtag/js?id=UA-39155502-5"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());
  
      gtag('config', 'UA-39155502-5');
    </script>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Paged search | MongoDB.Entities </title>
    <meta name="viewport" content="width=device-width">
    <meta name="title" content="Paged search | MongoDB.Entities ">
    <meta name="generator" content="docfx 2.58.0.0">
    <meta name="description" content="A data access library for MongoDB with an elegant api, LINQ support and built-in entity relationship management.">
    <link rel="shortcut icon" href="../images/favicon.ico">
    <link rel="stylesheet" href="../styles/docfx.vendor.css">
    <link rel="stylesheet" href="../styles/docfx.css">
    <link rel="stylesheet" href="../styles/main.css">
    <meta property="docfx:navrel" content="../toc.html">
    <meta property="docfx:tocrel" content="toc.html">
    
    <meta property="docfx:rel" content="../">
    <meta property="docfx:newtab" content="true">
    <meta property="og:title" content="MongoDB.Entities">
    <meta property="og:site_name" content="MongoDB.Entities">
    <meta property="og:url" content="https://mongodb-entities.com">
    <meta property="og:description" content="A data access library for MongoDB with an elegant api, LINQ support and built-in entity relationship management,">
    <meta property="og:type" content="website">
    <meta property="og:image" content="https://mongodb-entities.com/images/social-square.png">  
  </head>
  <body data-spy="scroll" data-target="#affix" data-offset="120">
    <div id="wrapper">
      <header>
        
        <nav id="autocollapse" class="navbar navbar-inverse ng-scope" role="navigation">
          <div class="container">
            <div class="navbar-header">
              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
              </button>
              
              <a class="navbar-brand" href="../index.html">
                <img id="logo" class="svg" src="../images/icon.png" alt="">
              </a>
            </div>
            <div class="collapse navbar-collapse" id="navbar">
              <form class="navbar-form navbar-right" role="search" id="search">
                <div class="form-group">
                  <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">
                </div>
              </form>
            </div>
          </div>
        </nav>
        
        <div class="subnav navbar navbar-default">
          <div class="container hide-when-search" id="breadcrumb">
            <ul class="breadcrumb">
              <li></li>
            </ul>
          </div>
        </div>
      </header>
      <div class="container body-content">
        
        <div id="search-results">
          <div class="search-list">Search Results for <span></span></div>
          <div class="sr-items">
            <p><i class="glyphicon glyphicon-refresh index-loading"></i></p>
          </div>
          <ul id="pagination" data-first="First" data-prev="Previous" data-next="Next" data-last="Last"></ul>
        </div>
      </div>
      <div role="main" class="container body-content hide-when-search">
        
        <div class="sidenav hide-when-search">
          <a class="btn toc-toggle collapse" data-toggle="collapse" href="#sidetoggle" aria-expanded="false" aria-controls="sidetoggle">Show / Hide Table of Contents</a>
          <div class="sidetoggle collapse" id="sidetoggle">
            <div id="sidetoc"></div>
          </div>
        </div>
        <div class="article row grid-right">
          <div class="col-md-10">
            <article class="content wrap" id="_content" data-uid="">
<h1 id="paged-search">Paged search</h1>

<p>paging in mongodb driver is typically achieved by running two separate db queries; one for the count and another for the actual entities. it can also be done via a <code>$facet</code> aggregation query, which is cumbersome to do using the driver. this library provides a convenient method for this exact use case via the <code>PagedSearch</code> builder.</p>
<h2 id="example">Example</h2>
<pre><code class="lang-csharp">var res = await DB.PagedSearch&lt;Book&gt;()
                  .Match(b =&gt; b.AuthorName == &quot;Eckhart Tolle&quot;)
                  .Sort(b =&gt; b.Title, Order.Ascending)
                  .PageSize(10)
                  .PageNumber(1)
                  .ExecuteAsync();

IReadOnlyList&lt;Book&gt; books = res.Results;
long totalMatchCount = res.TotalCount;
int totalPageCount = res.PageCount;                  
</code></pre>
<p>specify the search criteria with the <code>.Match()</code> method as you'd typically do. specify how to order the result set using the <code>.Sort()</code> method. specify the size of a single page using <code>.PageSize()</code> method. specify which page number to retrieve using <code>PageNumber()</code> method and finally issue the command using <code>ExecuteAsync()</code> to get the result of the facetted aggregation query.</p>
<p>the result is a value tuple consisting of the <code>Results</code>,<code>TotalCount</code>,<code>PageCount</code>.</p>
<div class="NOTE">
<h5>Note</h5>
<p>if you do not specify a matching criteria, all entities will match. the default page size is 100 if not specified and the 1st page is always returned if you omit it.</p>
</div>
<h2 id="project-results-to-a-different-type">Project results to a different type</h2>
<p>if you'd like to change the shape of the returned entity list, use the <code>PagedSearch&lt;T, TProjection&gt;</code> generic overload and add a <code>.Project()</code> method to the chain like so:</p>
<pre><code class="lang-csharp">var res = await DB.PagedSearch&lt;Book, BookListing&gt;()
                  .Sort(b =&gt; b.Title, Order.Ascending)
                  .Project(b =&gt; new BookListing
                  {
                      BookName = b.Title,
                      AuthorName = b.Author
                  })
                  .PageSize(25)
                  .PageNumber(1)
                  .ExecuteAsync();

IReadOnlyList&lt;BookListing&gt; listings = res.Results;
long totalMatchCount = res.TotalCount;
int totalPageCount = res.PageCount;                     
</code></pre>
<p><em>when projecting to different types as above, you may encounter a deserialization error thrown by the driver saying it can't convert <code>ObjectId</code> values to <code>string</code> in which case simply add a <code>.ToString()</code> to the property being projected like so:</em></p>
<pre><code class="lang-csharp">.Project(b =&gt; new BookListing
{
    ...
    BookID = b.ID.ToString(),
    ...
})
</code></pre>
<h2 id="paging-support-for-any-fluent-pipeline">Paging support for any fluent pipeline</h2>
<p>you can add paged search to any <a href="Queries-Pipelines.html">fluent pipeline</a>. the difference is, instead of specifying the search criteria with <code>.Match()</code>, you start off by using the <code>.WithFluent()</code> method like so:</p>
<pre><code class="lang-csharp">var pipeline = DB.Fluent&lt;Author&gt;()
                 .Match(a =&gt; a.Name == &quot;Author&quot;)
                 .SortBy(a =&gt; a.Name);

var res = await DB.PagedSearch&lt;Author&gt;()
                  .WithFluent(pipeline)
                  .Sort(a =&gt; a.Name, Order.Descending)
                  .PageNumber(1)
                  .PageSize(25)
                  .ExecuteAsync();
</code></pre>
<p>alternatively you can use the extension method on any fluent pipeline as well.</p>
<pre><code class="lang-csharp">var res = await pipeline.PagedSearch()
                        .Sort(a =&gt; a.Name, Order.Descending)
                        .PageSize(25)
                        .PageNumber(1)
                        .ExecuteAsync();
</code></pre>
<p>it's specially useful when you need to page children of a relationship like so:</p>
<pre><code class="lang-csharp">var res = await DB.Entity&lt;Author&gt;(&quot;AuthorID&quot;)
                  .Books
                  .ChildrenFluent()
                  .Match(b =&gt; b.Title.Contains(&quot;The&quot;))
                  .PagedSearch()
                  .Sort(b =&gt; b.Title, Order.Ascending)
                  .PageNumber(1)
                  .PageSize(10)
                  .ExecuteAsync();
</code></pre>
</article>
          </div>
          
          <div class="hidden-sm col-md-2" role="complementary">
            <div class="sideaffix">
              <div class="contribution">
                <ul class="nav">
                </ul>
              </div>
              <nav class="bs-docs-sidebar hidden-print hidden-xs hidden-sm affix" id="affix">
                <h5>In This Article</h5>
                <div></div>
              </nav>
            </div>
          </div>
        </div>
      </div>
      
      <footer>
        <div class="grad-bottom"></div>
        <div class="footer">
          <div class="container">
            <span class="pull-right">
              <a href="#top">Back to top</a>
            </span>
            Developed by <a href='https://github.com/dj-nitehawk'>Đĵ ΝιΓΞΗΛψΚ</a> and <a href='https://github.com/dj-nitehawk/MongoDB.Entities/graphs/contributors'>contributors</a> / Licensed under <a href='https://github.com/dj-nitehawk/MongoDB.Entities/blob/master/LICENSE'>MIT</a> / Website generated by <a href='https://dotnet.github.io/docfx/'>DocFX</a>
            
          </div>
        </div>
      </footer>
    </div>
    
    <script type="text/javascript" src="../styles/docfx.vendor.js"></script>
    <script type="text/javascript" src="../styles/docfx.js"></script>
    <script type="text/javascript" src="../styles/main.js"></script>
  </body>
</html>
